package public

import (
	"fmt"
	"goProject/api/auth"
	"goProject/db"
	"goProject/table"
	"net/http"
	"strings"
	"time"

	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
)

func refreshToken(c iris.Context) {
	myToken := c.GetHeader("Authorization")
	if strings.HasPrefix(myToken, "Bearer ") {
		myToken = myToken[7:]
	}
	if myToken == "" {
		c.JSON(std.NewResp(http.StatusOK, "token为空", "", ""))
		return
	}
	it, err := auth.ParseToken(myToken, c.RemoteAddr())
	if err != nil {
		c.JSON(std.NewResp(http.StatusOK, fmt.Sprint(err), "", ""))
		return
	}
	if str, _ := auth.Token.Get(fmt.Sprint(it.ID)); str != myToken {
		c.JSON(std.NewResp(http.StatusOK, "失效的token", "", ""))
		return
	}
	if time.Now().Unix()+600 > it.Expiry {
		var u table.User
		err = db.MySQL.Where("`id` = ?", it.ID).First(&u).Error
		if err == nil {
			myToken = auth.NewToken(u, c.RemoteAddr())
			_ = auth.Token.Set(fmt.Sprint(u.ID), myToken)
			c.JSON(std.NewResp(http.StatusOK, "新token", myToken, ""))
			return
		}
	}
	c.JSON(std.NewResp(http.StatusOK, "旧token", myToken, ""))
}
